<template>
  <div id="daily-report">
    <div class="daily-report-content">
      <div class="daily-report-item" v-for="(item, index) in dailyReportData" :key="index"
        @click="handleVideoClick(index)">
        <div class="item-cover">
          <img :src="item.cover?.feed || ''" alt="">
          <van-icon name="play" color="#fff" size="25" />
        </div>
        <div class="item-bottom">
          <div class="item-avatar"
            :style="{ backgroundImage: item.author?.icon ? `url(${item.author.icon})` : 'none' }"></div>
          <div class="item-msg">
            <div class="item-title">{{ item.title || '' }}</div>
            <div class="item-desc">
              <div class="user-name">{{ item.author?.name || '未知用户' }}</div>
              <div class="tag"># {{ item.category || '' }}</div>
              <div class="video-time"><van-icon name="play" />{{ formatDuration(item.duration) }}</div>
            </div>
            <div class="load-more" v-if="isLoadingMore">
              <van-loading type="spinner" color="#1989fa" />
              <span style="margin-left:8px;">数据正在加载中...</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { getSelected, getByFullUrl } from '@/api/api';
import { useVideoStore } from '@/stores/counter';

// 路由和 store
const router = useRouter();
const videoStore = useVideoStore();

// 数据状态
const dailyReportData = ref<any[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
const nextPageUrl = ref<string | null>(null);
const isLoadingMore = ref(false);
const hasMore = ref(true);

// 将秒数转换为 MM:SS 格式
const formatDuration = (seconds: number): string => {
  if (!seconds || seconds < 0) return '00:00';

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  const minutesStr = String(minutes).padStart(2, '0');
  const secondsStr = String(remainingSeconds).padStart(2, '0');

  return `${minutesStr}:${secondsStr}`;
};

// 处理视频点击事件
const handleVideoClick = (index: number) => {
  // 将当前点击的视频数据存入 store
  videoStore.setCurrentVideo(dailyReportData.value[index]);

  // 跳转到视频页面
  router.push('/video');
};

// 获取首页精选内容（首屏）
const fetchDailyReportData = async () => {
  loading.value = true;
  error.value = null;

  try {
    const data: any = await getSelected();
    if (data.itemList && data.itemList.length > 0) {
      // 过滤出视频类型的数据，并验证数据完整性
      data.itemList.forEach((item: any) => {
        if (item.type === 'video' && item.data) {
          // 验证必要字段存在
          if (item.data.cover && item.data.cover.feed) {
            dailyReportData.value.push(item.data);
          }
        }
      });
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);
  } catch (err) {
    console.error('获取首页精选失败:', err);
  } finally {
    loading.value = false;
  }
};

// 规范化 nextPageUrl，使用本地代理（开发环境）
const normalizeNextUrl = (url: string): string => {
  if (!url) return '';
  try {
    const u = new URL(url);
    return u.pathname + u.search;
  } catch {
    return url;
  }
};

// 加载更多（触底）
const loadMore = async () => {
  if (isLoadingMore.value || !hasMore.value || !nextPageUrl.value) return;
  isLoadingMore.value = true;

  try {
    const url = normalizeNextUrl(nextPageUrl.value);
    // 使用 getByFullUrl API 工具函数
    const data: any = await getByFullUrl(url.startsWith('/') ? url : `/${url}`);
    if (data?.itemList?.length) {
      data.itemList.forEach((item: any) => {
        if (item.type === 'video' && item.data) {
          // 验证必要字段存在，确保数据完整性
          if (item.data.cover && item.data.cover.feed) {
            dailyReportData.value.push(item.data);
          }
        }
      });
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);
  } catch (e) {
    console.error('加载更多失败:', e);
  } finally {
    isLoadingMore.value = false;
  }
};

// 监听滚动
const handleScroll = () => {
  // 获取滚动容器
  const scrollContainer = document.querySelector('.router-view-container > div') as HTMLElement;
  if (!scrollContainer) return;

  const scrollTop = scrollContainer.scrollTop;
  const viewH = scrollContainer.clientHeight;
  const docH = scrollContainer.scrollHeight;

  // 当滚动到距离底部 120px 时触发加载
  if (scrollTop + viewH >= docH - 120) {
    loadMore();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchDailyReportData();
  // 等待 DOM 更新后再绑定滚动事件
  nextTick(() => {
    // 监听容器的滚动事件
    const scrollContainer = document.querySelector('.router-view-container > div');
    if (scrollContainer) {
      scrollContainer.addEventListener('scroll', handleScroll, { passive: true });
    }
  });
});

onBeforeUnmount(() => {
  const scrollContainer = document.querySelector('.router-view-container > div');
  if (scrollContainer) {
    scrollContainer.removeEventListener('scroll', handleScroll as any);
  }
});
</script>

<style scoped lang="less">
#daily-report {
  width: 100%;
  min-height: 88vh;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2vh 0;
  color: #666;
  font-size: 12px;
}

.daily-report-content {
  width: 100%;
  padding-bottom: 7vh;

  .daily-report-item {
    width: 100%;
    cursor: pointer;

    .item-cover {
      position: relative;

      >i {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 1;
      }

      img {
        width: 100%;
      }
    }
  }
}

.item-bottom {
  width: 100%;
  height: 10vh;
  display: flex;
  align-items: flex-start;
  gap: 2vh;
  padding: 1vh 0;
  padding-left: 4vw;
  box-sizing: border-box;

  .item-avatar {
    height: 50%;
    aspect-ratio: 1/1;
    border-radius: 50%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }

  .item-msg {
    display: flex;
    flex-direction: column;
    gap: 1vh;

    .item-title {
      font-size: 12px;
    }

    .item-desc {
      display: flex;
      align-items: center;
      gap: 1vh;
      font-size: 10px;
      font-weight: 300;
    }
  }
}
</style>
